package com.fenghuajueli.module_host

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.fenghuajueli.libbasecoreui.BaseApplication
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyV3Helper
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyV4Helper
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyV4Helper.adModeConfig
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyV4Helper.getAdSwitch
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyV4Helper.getLocalToponAppkey
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo
import com.fenghuajueli.libbasecoreui.constants.ConfigConstants
import com.fenghuajueli.libbasecoreui.data.adv4.AdV4Type
import com.fenghuajueli.libbasecoreui.data.entity.ad.AdTypeConfig
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils
import com.fenghuajueli.libbasecoreui.utils.MyStatusBarUtils
import com.fenghuajueli.libbasecoreui.utils.PrivacyDialogBuilder
import com.fenghuajueli.libbasecoreui.utils.PrivacyDialogConfig
import com.fenghuajueli.libbasecoreui.utils.PrivacyDialogConfig.PrivacyDialogListener
import com.fenghuajueli.module_host.databinding.ActivityLauncherBinding
import com.fenghuajueli.module_host.utils.LaunchState
import com.fenghuajueli.module_host.utils.LauncherViewModel
import com.fenghuajueli.module_route.CommonRoute
import com.sy.lib_base_ad.AdConfig
import com.sy.lib_base_ad.TopOnNetworkPlatform
import com.sy.module_ad_switch_manager.AdShowHelper
import com.sy.module_ad_switch_manager.AdSwitchManger
import com.sy.module_ad_switch_manager.AdType
import kotlinx.coroutines.launch

@Route(path = CommonRoute.COMMON_LAUNCHER)
class LauncherActivity : AppCompatActivity() {

    private var binding: ActivityLauncherBinding? = null
    private val viewModel by viewModels<LauncherViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLauncherBinding.inflate(layoutInflater)
        setContentView(binding!!.root)
        MyStatusBarUtils.setStatusBar(this, "#00FFFFFF")

        showDialog()
    }

    private fun showDialog() {
        if (!MmkvUtils.get(ConfigConstants.MMKVKEY.privacyDialogIsShow.name, false)) {
            val privacyAgreementDialog = PrivacyDialogBuilder.create(this)
                .setDialogStyle(PrivacyDialogConfig.DIALOG_STYLE_WHITE_1)
                .setCancelName("拒绝并退出") //可以不用设置  默认就是这个文案
                .setConfirmName("阅读并同意")
                .setDialogTitle("温馨提示")
                .setReplayCompanyName(AppConfigInfo.APP_COMPANY)
                .setReplayAppName(AppConfigInfo.APP_NAME)
                .setCustomJump(false)
                .setPrivacyDialogListener(object : PrivacyDialogListener {
                    override fun cancel() {
                        finish()
                    }

                    override fun confirm() {
                        //一旦用户同意了协议之后 就要初始化第三方的SDK,这里的逻辑修改了界面之后也要记得加上
                        //这里做一下延迟初始化 防止第一次启动时 广告未初始化成功 导致第一次不展示开屏的问题
                        BaseApplication.getApplication().initThirdSdk()
                        getSwitchKey()
                    }

                    override fun clickPrivacyText() {}
                    override fun clickAgreementText() {}
                })
                .build()
            privacyAgreementDialog.setCancelable(false)
            privacyAgreementDialog.show()
        } else {
            getSwitchKey()
        }
    }

    override fun onDestroy() {
        binding = null
        super.onDestroy()
    }

    private fun goMain() {
        if (isTaskRoot) {
            ARouter.getInstance().build(CommonRoute.COMMON_MAIN).navigation()
        }
        finish()
    }

    override fun onBackPressed() {
        //启动页不响应返回操作
    }

    private fun loadAd() {
        AdShowHelper.checkTimeCanShowAd(
            false,
            getAdSwitch(),
            "AdShowHelperKEY_V3_SPLASH_SHOWED",
            "启动开屏",
            AdShowHelper.adModeConfig?.open_screen
        ) { showAd ->
            if (showAd || isTaskRoot) {
                LogUtils.d("loadAd: 调用开屏加载广告")
                lifecycleScope.launch {
                    //广告开关打开 加载广告
                    AdShowHelper.showSplashAd(
                        getAdSwitch(),
                        this@LauncherActivity,
                        binding!!.splashAdContainer
                    ) {
                        goMain()
                    }
                }
            } else {
                LogUtils.d("loadAd: 跳过开屏广告")
                finish()
            }
        }
    }

    fun getSwitchKey() {
        initTestData()
        viewModel.getSwitchKey()

        lifecycleScope.launch {
            //获取v2广告及其他配置。广告配置和v3相互独立。
            launch {
                viewModel.v2Switch
                    .flowWithLifecycle(lifecycle)
                    .collect {
                        when (it) {
                            LaunchState.Success -> {
//                                UploadUtils.openAction(this@LauncherActivity, application)
                            }

                            else -> Unit
                        }
                    }
            }

            //从v3接口请求广告配置
            launch {
                viewModel.v3Switch
                    .flowWithLifecycle(lifecycle)
                    .collect {
                        when (it) {
                            LaunchState.Success -> {
                                LogUtils.d("getSwitchKey: 开始处理V3逻辑 $it")
                                initAdSdkV3()
                            }

                            LaunchState.Fail -> goMain()
                            LaunchState.Default -> Unit
                        }
                    }
            }

            //从v4接口请求广告配置
            launch {
                viewModel.v4Switch
                    .flowWithLifecycle(lifecycle)
                    .collect {
                        when (it) {
                            LaunchState.Success -> {
                                LogUtils.d("v4广告id初始化$it~")
                                SwitchKeyV4Helper.calculateAdTypeConfigs.forEach { adconfig ->
                                    LogUtils.d("初始化广告: " + adconfig.type, adconfig.toString())
                                    initAdSdkV4(adconfig)
                                }
                            }

                            else -> Unit
                        }
                    }
            }
        }
    }

    private fun initAdSdkV3() {
        val adConfig = AdConfig().apply {
            adAppId = SwitchKeyV3Helper.getAdAppIdV3() //appid
            splashId = SwitchKeyV3Helper.getSplashIdV3() //开屏id
            interactionId = SwitchKeyV3Helper.getInsertHalfIdV3() //插屏的id
            bannerId = SwitchKeyV3Helper.getBannerIdV3() //banner的id
            fullScreenVideoId = SwitchKeyV3Helper.getFullScreenVideoIdV3() //全屏广告的id
            rewardVideoId = SwitchKeyV3Helper.getRewardIdV3() //激励视频广告的id
            informationFlowId = SwitchKeyV3Helper.getInfoFlowIdV3() //模板渲染信息流的id
            adAppKey = SwitchKeyV3Helper.getLocalToponAppkey() //Topon广告平台专用
            wXAppId = AppConfigInfo.WECHAT_APP_ID //微信appid，Topon广告需要（可不填），广告用来跳微信小程序
        }

        initCsjSplashData(adConfig, SwitchKeyV3Helper.getAdType() == AdType.ADTYPE_GM)
        initTopOnData()
        AdSwitchManger.initAdSdkV3(
            application,
            AppConfigInfo.APP_DEBUG,
            SwitchKeyV3Helper.getAdType(),
            adConfig,
            SwitchKeyV3Helper.getV3ModeConfig()
        ) { initSdkSuccess: Boolean ->
            //不用判断SDK是不是初始化成功，调用开屏广告时内部会做判断
            loadAd()
        }
    }

    private fun initAdSdkV4(adTypeConfig: AdTypeConfig) {
        //开关获取成功后 才初始化广告sdk
        val adConfig = AdConfig().apply {
            adAppId = adTypeConfig.appId //appid
            splashId = adTypeConfig.openScreenId //开屏id
            interactionId = adTypeConfig.newInsertHalfScreenId //插屏的id
            bannerId = adTypeConfig.bannerId //banner的id
            fullScreenVideoId = adTypeConfig.newInsertFullScreenId //全屏广告的id
            rewardVideoId = adTypeConfig.incentiveVideoId //激励视频广告的id
            informationFlowId = adTypeConfig.imformationID //模板渲染信息流的id
            adAppKey = getLocalToponAppkey() //Topon广告平台专用
            wXAppId = AppConfigInfo.WECHAT_APP_ID //微信appid，Topon广告需要（可不填），广告用来跳微信小程序
        }

        initCsjSplashData(adConfig, adTypeConfig.type == AdType.ADTYPE_GM)
        initTopOnData()

        AdSwitchManger.initAdSdkV4Ad(
            application,
            AppConfigInfo.APP_DEBUG,
            adTypeConfig.type,
            adConfig,
            adModeConfig
        ) { initSdkSuccess ->
            if (AdV4Type.adOpenScreenIdType == adTypeConfig.type) {
                //不用判断SDK是不是初始化成功，调用开屏广告时内部会做判断
                loadAd()
            }
        }
    }

    private fun initTestData() {
        //测试广告开关，目的是：当广告ID没开启测试状态时，减少广告调用次数(避免判违规)
//        AdSwitchManger.debugTest = true
        //提供release包广告吐司提示,穿山甲\TopOn生效哦
//        AdSwitchManger.testToast = true
    }

    private fun initTopOnData() {
//        AdSwitchManger.setTopOnDebuggerPlatform(TopOnNetworkPlatform.ADX_NETWORK) //指定TopOn测试平台,仅在测试模式生效
    }

    private fun initCsjSplashData(adConfig: AdConfig, useMediation: Boolean) {
        adConfig.csjUseMediation = useMediation //穿山甲是否开启聚合功能
        //这2中不能同时使用
//        if (useMediation) {
//            adConfig.csjSplashRequestInfo = SplashRequestInfo(
//                CsjNetworkPlatform.ADN_PANGLE,
//                "",  // adn开屏广告代码位Id，注意不是聚合广告位Id,运营会给
//                adConfig.adAppId,  //adn应用id，注意要跟初始化传入的保持一致
//                adConfig.adAppKey //adn没有appKey时，传入空即可
//            ) //穿山甲开屏自定义兜底对象，参数由运营导出
//        } else {
//            val s = """
//                    {"cypher":2,"message":""}
//                    """.trimIndent()
//            adConfig.splashConfig = s //穿山甲、TopOn开屏冷启动参数，由运营导出
//        }
    }
}